package mrdog.captor;

import java.util.concurrent.LinkedBlockingQueue;

import jpcap.packet.Packet;

class BlockingPacketPool implements PacketPool {

	private LinkedBlockingQueue<Packet> rawPacket = null;
	
	private int MAX_POOL_SIZE = 0;
	
	public int DROP_PACKET = 0;
	
	Object lock = new Object();
	
	public BlockingPacketPool(int capacity){
		if(capacity > 0) {
			MAX_POOL_SIZE = capacity;
		}
		rawPacket = new LinkedBlockingQueue<Packet>(MAX_POOL_SIZE);
	}
	
	public void add(Packet packet) {
		if(!rawPacket.offer(packet)) {
			synchronized (lock) {
				++ DROP_PACKET;
			}
		}
	}

	public Packet get() {
		try {
			return rawPacket.take();
		} 
		catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}

	public int size() {
		return rawPacket.size();
	}

	public void clear() {
		 rawPacket = new LinkedBlockingQueue<Packet>(MAX_POOL_SIZE);
	}

	public int maxSize() {
		return MAX_POOL_SIZE;
	}
}
